<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'

import { useAddEnterpriseCustomer, useEditEnterpriseCustomer, useGetEnterpriseCustomerDetail } from '@fl/api/supplier'
import FlUpload from '@fl/components/fl-upload.vue'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { jsonToArray } from '@fl/utils/fn'
import { cloneDeep } from 'lodash-es'

const id = defineModel<string>('id', { required: true })
const visible = defineModel<boolean>('visible', { required: true })

const initialState = {
    caseFileList: [],
    contractFileList: [],
} as any
const state = ref(cloneDeep(initialState))

const isEdit = computed(() => !!id.value)
const dialogTitle = computed(() => isEdit.value ? '编辑合作客户' : '新增合作客户')

const { isPending: isAddEnterpriseCustomerPending, mutate: addEnterpriseCustomer } = useAddEnterpriseCustomer()
const { isPending: isEditEnterpriseCustomerPending, mutate: editEnterpriseCustomer } = useEditEnterpriseCustomer()
const { data: enterpriseCustomerDetailData, isLoading: isGetEnterpriseCustomerDetailLoading } = useGetEnterpriseCustomerDetail(id)

// #region Form
const formRef = ref()
const isFormLoading = computed(() => isGetEnterpriseCustomerDetailLoading.value)
const isSubmitLoading = computed(() => isEdit.value ? isEditEnterpriseCustomerPending.value : isAddEnterpriseCustomerPending.value)

const columns: PlusColumn[] = [
    {
        label: '合作客户名称',
        prop: 'name',
        valueType: 'copy',
    },
    {
        fieldProps: {
            valueFormat: 'YYYY-MM-DD',
        },
        label: '开始合作时间',
        prop: 'startTime',
        valueType: 'date-picker',
    },
    {
        label: '上年度合作金额',
        prop: 'money',
    },
    {
        label: '合同附件',
        prop: 'contractFileList',
    },
    {
        label: '案例附件',
        prop: 'caseFileList',
    },
]

const rules = {
    name: [
        {
            message: '请输入合作客户名称',
            required: true,
            trigger: 'change',
        },
    ],
    startTime: [
        {
            message: '请选择开始合作时间',
            required: true,
            trigger: 'change',
        },
    ],
}
// #endregion

// #region UI Listener
function onSubmitBtnClick() {
    formRef.value.handleSubmit()
}

function submit() {
    const data = cloneDeep(state.value)
    const params = {
        ...data,
        caseFile: JSON.stringify(data.caseFileList),
        caseFileList: undefined,
        contractFile: JSON.stringify(data.contractFileList),
        contractFileList: undefined,
    }

    const fn = isEdit.value ? editEnterpriseCustomer : addEnterpriseCustomer
    fn(params, {
        onSuccess() {
            ElMessage.success('操作成功')
            closed()
        },
    })
}

function onCancelBtnClick() {
    closed()
}

function closed() {
    visible.value = false
    if (isEdit.value) {
        id.value = ''
    }
    else {
        state.value = cloneDeep(initialState)
        formRef.value.formInstance?.resetFields()
    }
}
// #endregion

watchEffect(() => {
    if (isEdit.value && enterpriseCustomerDetailData.value) {
        const data = cloneDeep(enterpriseCustomerDetailData.value)
        const caseFileList = jsonToArray(data.caseFile)
        const contractFileList = jsonToArray(data.contractFile)
        Object.assign(state.value, data, {
            caseFileList,
            contractFileList,
        })
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialogTitle"
                width="700"
                close-on-press-escape
                @closed="closed"
    >
        <el-skeleton v-if="isFormLoading"
                     animated
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="130"
                  :rules="rules"
                  :has-footer="false"
                  @submit="submit"
        >
            <template #plus-field-money>
                <el-input v-model="state.money"
                          type="number"
                          placeholder="请输入上年度合作金额"
                >
                    <template #append>
                        <span>万元</span>
                    </template>
                </el-input>
            </template>

            <template #plus-field-contractFileList>
                <FlUpload v-model="state.contractFileList"
                          tips
                          accept=".doc,.docx,.pdf,.jpg,.jpeg,.png"
                          list-type="text"
                />
            </template>

            <template #plus-field-caseFileList>
                <FlUpload v-model="state.caseFileList"
                          tips
                          accept=".doc,.docx,.pdf,.jpg,.jpeg,.png"
                          list-type="text"
                />
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="onCancelBtnClick">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isSubmitLoading"
                           @click="onSubmitBtnClick"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
